import { defineStore } from 'pinia'
import axios from 'axios'
import { useAuthStore } from './auth'

export const useCommentStore = defineStore('comment', {
  state: () => ({
    comments: [],
    loading: false,
    error: null
  }),
  
  actions: {
    async fetchCommentsByBlog(blogId) {
      this.loading = true
      try {
        const response = await axios.get(`/api/comment/blog/${blogId}`)
        // 处理每条评论的用户头像
        const comments = response.data.map(comment => {
          // 确保用户信息存在
          if (comment.user && !comment.user.avatar && comment.user.userId) {
            // 获取用户头像并添加到评论对象中
            this.fetchUserAvatar(comment.user.userId).then(avatar => {
              if (avatar) {
                if (!comment.user.avatar) {
                  comment.user.avatar = avatar;
                }
              }
            }).catch(error => {
              console.error('获取用户头像失败:', error);
            });
          }
          
          // 处理回复的头像
          if (comment.replies && comment.replies.length > 0) {
            comment.replies.forEach(reply => {
              if (reply.user && !reply.user.avatar && reply.user.userId) {
                this.fetchUserAvatar(reply.user.userId).then(avatar => {
                  if (avatar) {
                    if (!reply.user.avatar) {
                      reply.user.avatar = avatar;
                    }
                  }
                }).catch(error => {
                  console.error('获取回复用户头像失败:', error);
                });
              }
            });
          }
          
          return comment;
        })
        
        this.comments = comments
        return comments
      } catch (error) {
        this.error = error.response?.data?.message || '获取评论失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    async fetchUserAvatar(userId) {
      try {
        const response = await axios.get(`/api/image/user/${userId}/avatar`);
        if (response.data.success && response.data.avatar) {
          // 确保返回的avatar对象有imageName属性
          const avatar = response.data.avatar;
          if (!avatar.imageName && avatar.imagePath) {
            // 如果只有路径，尝试提取文件名
            const parts = avatar.imagePath.split('/');
            const fileName = parts[parts.length - 1];
            if (fileName) {
              avatar.imageName = fileName;
            }
          }
          return avatar;
        }
        return null;
      } catch (error) {
        console.error('获取用户头像失败:', error);
        return null;
      }
    },
    
    async addComment(commentData) {
      this.loading = true
      try {
        // 从本地存储获取用户 ID
        const userId = JSON.parse(localStorage.getItem('user'))?.userId;
        
        // 确保评论数据包含用户 ID
        const commentPayload = {
          ...commentData,
          userId: userId
        };
        
        console.log('发送评论数据:', commentPayload);
        
        const response = await axios.post('/api/comment/add', commentPayload);
        
        // 检查响应是否成功
        if (!response.data.success) {
          throw new Error(response.data.message || '添加评论失败');
        }
        
        // 重新获取评论列表，确保数据一致
        await this.fetchCommentsByBlog(commentData.blogId);
        
        return response.data;
      } catch (error) {
        console.error('添加评论失败:', error);
        this.error = error.response?.data?.message || error.message || '添加评论失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    async addReply(replyData) {
      this.loading = true
      try {
        // 从本地存储获取用户 ID
        const userId = JSON.parse(localStorage.getItem('user'))?.userId;
        
        // 确保回复数据包含用户 ID
        const replyPayload = {
          ...replyData,
          userId: userId
        };
        
        console.log('发送回复数据:', replyPayload);
        
        const response = await axios.post('/api/comment/reply', replyPayload);
        
        // 检查响应是否成功
        if (!response.data.success) {
          throw new Error(response.data.message || '添加回复失败');
        }
        
        // 找到要回复的评论所属的博客ID
        const blogId = this.comments.find(c => c.commentId === replyData.commentId)?.blogId;
        
        if (blogId) {
          // 重新获取评论以更新回复
          await this.fetchCommentsByBlog(blogId);
        }
        
        return response.data;
      } catch (error) {
        console.error('添加回复失败:', error);
        this.error = error.response?.data?.message || error.message || '添加回复失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    async deleteComment(commentId) {
      this.loading = true
      try {
        const response = await axios.delete(`/api/comment/${commentId}`);
        if (response.data.success) {
          // 从本地状态中移除评论
          this.comments = this.comments.filter(comment => comment.commentId !== commentId);
          return true;
        } else {
          throw new Error(response.data.message || '删除评论失败');
        }
      } catch (error) {
        this.error = error.response?.data?.message || error.message || '删除评论失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    async deleteReply(userId, commentId) {
      this.loading = true
      try {
        const response = await axios.delete(`/api/comment/reply?userId=${userId}&commentId=${commentId}`);
        if (response.data.success) {
          // 更新本地状态中的评论
          this.comments = this.comments.map(comment => {
            if (comment.commentId === commentId) {
              return {
                ...comment,
                replies: comment.replies?.filter(reply => 
                  !(reply.userId === userId && reply.commentId === commentId)
                ) || []
              };
            }
            return comment;
          });
          return true;
        } else {
          throw new Error(response.data.message || '删除回复失败');
        }
      } catch (error) {
        this.error = error.response?.data?.message || error.message || '删除回复失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    // 管理员禁用评论
    async toggleCommentStatus(commentId, isDisabled) {
      this.loading = true;
      try {
        const authStore = useAuthStore();
        if (!authStore.isAdmin) {
          throw new Error('没有权限执行此操作');
        }
        
        const response = await axios.put(`/api/comment/admin/toggle-status/${commentId}`, null, {
          params: { isDisabled }
        });
        
        if (response.data.success) {
          // 更新本地状态
          this.comments = this.comments.map(comment => {
            if (comment.commentId === commentId) {
              return { ...comment, isDisabled };
            }
            return comment;
          });
          return true;
        } else {
          throw new Error(response.data.message || '操作失败');
        }
      } catch (error) {
        this.error = error.response?.data?.message || error.message || '操作失败';
        throw error;
      } finally {
        this.loading = false;
      }
    }
  }
}) 